﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpSoft.Documentation.Html.CSS
{
    /// <summary>
    /// CSS属性解析器
    /// </summary>
    internal class CssPropertiesParser
    {
        public CssPropertiesParser(string source)
        {
            _Lexer = new CssPropertiesLexer(source);
        }
        public CssPropertiesParser(SharpSoft.Lexing.TextSource source)
        {
            _Lexer = new CssPropertiesLexer(source);
        }

        private readonly CssPropertiesLexer _Lexer;

        public CssPropertyCollection Parse()
        {
            List<CssPropertiesToken> list = new List<CssPropertiesToken>(30);
            CssPropertiesToken t = _Lexer.ReadToken();
            while (t != null)
            {
                list.Add(t);
                t = _Lexer.ReadToken();
            }
            CssPropertyCollection col = new CssPropertyCollection();
            for (int i = 0; i < list.Count; i += 2)
            {
                var name = list[i];
                if (name.Type != CssPropertiesTokenType.PropertyName)
                    throw new CssSyntaxException(name.Position, name.Length, "此处应为属性名称。");
                var value = list[i + 1];
                if (value.Type != CssPropertiesTokenType.PropertyValue)
                    throw new CssSyntaxException(name.Position, name.Length, "此处应为属性值。");
                col.Add(name.Content, value.Content);
            }
            return col;
        }

        public static CssPropertyCollection Parse(string source)
        {
            CssPropertiesParser p = new CssPropertiesParser(source);
            return p.Parse();
        }
    }
}
